package seig.wjy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import seig.wjy.domain.pojo.User;
import seig.wjy.mapper.UserMapper;
import seig.wjy.service.RegisterService;
import seig.wjy.tools.AppHttpCodeEnum;
import seig.wjy.tools.ResponseResult;

/**
 * @author wu
 */
@Service
public class RegisterServiceImpl extends ServiceImpl<UserMapper, User> implements RegisterService {
    private UserMapper userMapper;
    private PasswordEncoder passwordEncoder;
    @Autowired
    public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }
    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }
    @Override
    public ResponseResult register(User user) {
        try {
            // 加密密码
            String userPassword = user.getPassword();
            String encodedPassword = passwordEncoder.encode(userPassword);
            user.setPassword(encodedPassword);

            // 尝试插入用户，如果account已存在，数据库将抛出异常
            int rowsAffected = userMapper.insert(user);
            if (rowsAffected == 1) {
                return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
            } else {
                return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);
            }
        } catch (DataIntegrityViolationException e) {
            System.out.println("DuplicateKeyException");
            return ResponseResult.errorResult(AppHttpCodeEnum.ACCOUNT_EXIST);
        } catch (Exception e) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);
        }
    }
}
